package org.andromeo.connectionapi;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.andromeo.ARException;
import org.andromeo.ARUtil;
import org.andromeo.GRSession;
import org.andromeo.Message;
import org.andromeo.MessageFactory;
import org.andromeo.User;
import org.andromeo.util.ARRequester;
import org.andromeo.util.StringUtils;

public class SingleMsgExtractor {

	private static Pattern messagePattern1 = Pattern.compile(
			"<div class=\"msg\".*?<div.*?>(.*?)</div.*?(<form id=\"msgForm\")",
			Pattern.DOTALL);

	private static Pattern messagePattern2 = Pattern.compile(
			"<div class=\"msg\".*?<div.*?>(.*?)</div", Pattern.DOTALL);

	private static Pattern useridPattern = Pattern
			.compile("\\.\\./auswertung/setcard\\?set=(\\d*).*>(.*)</a>",
					Pattern.DOTALL);

	private static Pattern xsrfPattern = Pattern.compile(
			"<form\\s.*name=\"xsrfprotect\"\\s+value=\"(\\w*)\"",
			Pattern.DOTALL);

	private static Pattern imgurlPattern = Pattern
			.compile("<a\\s.*?href=\"(.*?)\".*?target=\"picpopup\"");

	private static Pattern imgthumbUrlPattern = Pattern
			.compile("<img\\s.*?src=\"(.*?)\".*?>");

	private static Pattern datetimePattern = Pattern
			.compile("\\d\\d\\.&nbsp;\\w{3}\\.&nbsp;\\d{4}&nbsp;-&nbsp;\\d\\d:\\d\\d");

	private static SimpleDateFormat sdtf = new SimpleDateFormat(
			"dd. MMM. yyyy - HH:mm",new Locale("en"));

	public GRSession grsession = null;

	public static synchronized Message getMessageDetailed(GRSession grsession,
			User user, String previousmessageid, int messagetype)
			throws ARException, UnsupportedEncodingException, IOException {

		@SuppressWarnings("unused")
		String uid = null;
		@SuppressWarnings("unused")
		String uname = null;
		String xsrf = null;
		String text = "";
		Date date = new Date();
		// using a map here that contains the url to the image and the url to
		// the link, does complicate things when parsing and doesn't really add
		// any value (we still must rely that they appear in pairs..) thus using
		// two ArrayLists that preserver their order.

		Message msg = MessageFactory.getMessageFactory(grsession)
				.getMessageById(previousmessageid);

		if (msg.isMsgComplete()) {
			// Message has been read before completely so no reread is needed
			return msg;
		} else {
			// read the message information
			List<String> images = new ArrayList<String>();

			List<String> imageLinks = new ArrayList<String>();

			// set URL path depends on parameters (if a prevmessageid is given,
			// then
			// use this as parameter for retrieving the message details
			String urlpath = "http://www.gayromeo.com/".concat(
					grsession.getPhpSessionID()).concat("/msg/?");

			if (messagetype == Message.SENT_MESSAGE) {
				urlpath += "type=sent&";
			}

			if (previousmessageid == null || previousmessageid.length() == 0)
				urlpath += "uid=" + user.getUserID();
			else
				urlpath += "id=" + previousmessageid;

			// Send request
			String response = ARRequester.sendRequest(grsession, urlpath, "");
			// Site parsing
			Matcher messageMatcher1 = messagePattern1.matcher(response);
			Matcher messageMatcher2 = messagePattern2.matcher(response);
			Matcher useridMatcher = useridPattern.matcher(response);
			Matcher xsrfMatcher = xsrfPattern.matcher(response);
			Matcher imgthumbMatcher = imgthumbUrlPattern.matcher(response);
			Matcher imgurlMatcher = imgurlPattern.matcher(response);
			Matcher datetimeMatcher = datetimePattern.matcher(response);

			// Extract information
			if (useridMatcher.find()) {
				uid = useridMatcher.group(1);
				uname = useridMatcher.group(2);
			}

			// message text extraction works as follows:
			// if xsrf-attr is found (and a form for message sending will be
			// shown)
			// then use messagePattern1 for message-content
			// This is not very clean but works!
			if (xsrfMatcher.find()) {
				xsrf = xsrfMatcher.group(1);
				if (messageMatcher1.find()) {
					text += messageMatcher1.group(1);
					text = StringUtils.unescapeHTML(text, 0);
					text = text.replaceAll("<.*?>", "");
				}
			} else if (messageMatcher2.find()) {
				// no message-form is shown so use messagePattern2 for
				// extraction
				text += messageMatcher2.group(1);
				text = StringUtils.unescapeHTML(text, 0);
				text = text.replaceAll("<.*?>", "");
			}

			// Extract date and time
			if (datetimeMatcher.find()) {

				String datestring = datetimeMatcher.group(0);
				datestring = StringUtils.unescapeHTML(datestring, 0);
				try {
					date = sdtf.parse(datestring);
				} catch (ParseException e) {
					e.printStackTrace();
					date = null;
				}
			}

			while (imgthumbMatcher.find()) {
				images.add(imgthumbMatcher.group(1));
			}

			while (imgurlMatcher.find()) {
				imageLinks.add(ARUtil.siteurl + grsession.getPhpSessionID()
						+ imgurlMatcher.group(1));
			}

			msg.setMessageTicket(xsrf);
			if (text != null)
				msg.setFullText(text);
			
			if (date != null)
				msg.setMessageTimestamp(date);

			msg.setImageLinks(imageLinks);
			msg.setImages(images);

			// mark received message as read
			if (msg.getMessagetype() == Message.RECEIVED_MESSAGE)
				msg.setMarkNewMessage(false);

			// mark message that all informations has been extracted into AR
			// so no further extraction is needed
			msg.setMsgComplete(true);
			grsession.getMessageFactory().getNewMsgList().remove(msg);
			

			return msg;
		}

	}

}
